<?php

namespace common\helpers;

use Yii;

/**
 * UUID扩展操作函数
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class UuidHelper {

    public static function format($value = '') {
        if (strlen($value) < 32) {
            $value .= static::unique();
        }
        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(substr($value, 0, 32), 4));
    }

    public static function unique($prefix = '') {
        if ($prefix !== false && !$prefix) {
            $prefix = Yii::$app->id;
        }
        return md5(uniqid($prefix));
    }

    public static function create() {
        $uuid = '';
        if (function_exists('uuid_create') === true) {
            $uuid = uuid_create(1);
        } else {
            $data = openssl_random_pseudo_bytes(16);
            $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
            $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
            $uuid = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
        }
        return $uuid;
    }

}
